package com.szly.phm.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szly.phm.common.entity.dto.FaFault.*;
import com.szly.phm.common.entity.dto.ensure.*;
import com.szly.phm.common.entity.dto.user.LoginUserDTO;
import com.szly.phm.common.entity.po.*;
import com.szly.phm.common.entity.result.CodeStatusEnum;
import com.szly.phm.common.entity.result.PageResult;
import com.szly.phm.common.entity.result.RootResponse;
import com.szly.phm.common.entity.vo.Fault.FaPhenomenonRecordVO;
import com.szly.phm.common.entity.vo.Fault.FaPhenomenonVO;
import com.szly.phm.common.entity.vo.ensure.*;
import com.szly.phm.common.mapper.*;
import com.szly.phm.common.service.IEnsureService;
import com.szly.phm.common.utils.BeanCopyUtils;
import com.szly.phm.common.utils.HandleUtils;
import com.szly.phm.common.utils.PagingResultUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * phm
 *
 * @author: git.jas0nch
 * date: 2021-10-18
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EnsureServiceImpl implements IEnsureService {

    private final RaKeyPartsMapper raKeyPartsMapper;

    private final RaRadarMapper raRadarMapper;

    private final RaKeyPartsModelMapper raKeyPartsModelMapper;
    private final RaKeyPartsTypeMapper raKeyPartsTypeMapper;
    private final FaTaskLevelMapper faTaskLevelMapper;

    private final FaEnsurePlanMapper faEnsurePlanMapper;

    private final FaEnsureWaysMapper faEnsureWaysMapper;

    private final FaEnsureRecordMapper faEnsureRecordMapper;

    private final FaPhenomenonRecordMapper faPhenomenonRecordMapper;

    private final FaFaultRecordMapper faFaultRecordMapper;

    private final FaPhenomenonMapper faPhenomenonMapper;

    private final FaEnsureMapper faEnsureMapper;

    private final FaEnsureTypeMapper faEnsureTypeMapper;

    private final RaTreeMapper raTreeMapper;
    private final RaExtensionMapper raExtensionMapper;
    private final RaSystemMapper raSystemMapper;

    private final RaStationMapper raStationMapper;

    private final FiRadarTypeMapper fiRadarTypeMapper;

    @Override
    public RootResponse<EnsureEnsureType2StructureVO> queryEnsureEnsureType2Structure(EnsureEnsureType2StructurePageDTO ensureEnsureType2StructurePageDTO) {
        EnsureEnsureType2StructureVO ensureEnsureType2StructureVO = new EnsureEnsureType2StructureVO();
        ensureEnsureType2StructureVO.setStructureId(ensureEnsureType2StructurePageDTO.getStructureId());
        List<Ensure2ensureTypeBaseVO> ensureBaseList = new ArrayList<>();
        Set<String> ensureIds = new HashSet<>();
        RaTree raTree = raTreeMapper.selectById(ensureEnsureType2StructurePageDTO.getStructureId());
        // query:
        // ensure
        LambdaQueryWrapper<FaEnsurePlan> ensurePlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ensurePlanLambdaQueryWrapper.eq(FaEnsurePlan::getIsSoftDelete, false);
        ensurePlanLambdaQueryWrapper.eq(FaEnsurePlan::getStructureId, ensureEnsureType2StructurePageDTO.getStructureId());
        List<FaEnsurePlan> faEnsurePlans = faEnsurePlanMapper.selectList(ensurePlanLambdaQueryWrapper);
        //
        for (FaEnsurePlan elem : faEnsurePlans) {
            if (!StringUtils.isEmpty(elem.getEnsureId())) {
                Ensure2ensureTypeBaseVO ensure2ensureTypeBaseVO = new Ensure2ensureTypeBaseVO();
                //
                ensure2ensureTypeBaseVO.setId(elem.getEnsureId());
                //
                Set<String> ensureTypes = new HashSet<>();
                for (FaEnsurePlan temp : faEnsurePlans) {
                    if (temp.getEnsureId().equals(elem.getEnsureId()) && !StringUtils.isEmpty(temp.getEnsureTypeId())) {
                        ensureTypes.add(temp.getEnsureTypeId());
                    }
                }
                ensure2ensureTypeBaseVO.setTypeIdList(ensureTypes);
                if (!ensureIds.contains(ensure2ensureTypeBaseVO.getId())) {// ensure id如果不在里面就添加
                    ensureBaseList.add(ensure2ensureTypeBaseVO);
                }
                // 这里注意和上一个if条件的顺序，这里以deBug修改
                ensureIds.add(elem.getEnsureId()); // 添加保障id集合，之后添加到vo的时候去重用
            }
        }
        ensureEnsureType2StructureVO.setEnsureBaseList(ensureBaseList);
        return RootResponse.success(ensureEnsureType2StructureVO);
    }

    @Override
    public RootResponse<FaEnsure2StructureVO> queryEnsure2Structure(EnsureStructurePageDTO ensureStructurePageDTO) {
        FaEnsure2StructureVO ensure2StructureVO = new FaEnsure2StructureVO();
        RaTree raTree = raTreeMapper.selectById(ensureStructurePageDTO.getStructureId());
        // query:
        // key part
        LambdaQueryWrapper<FaEnsure> ensureLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ensureLambdaQueryWrapper.eq(FaEnsure::getIsSoftDelete, false);
        ensureLambdaQueryWrapper.eq(FaEnsure::getKeyPartsId, ensureStructurePageDTO.getKeyPartId());
        List<String> keyPart2ensureIds = new ArrayList<>();
        List<String> extension2ensureIds = new ArrayList<>();
        List<String> system2ensureIds = new ArrayList<>();
        for (FaEnsure elem : faEnsureMapper.selectList(ensureLambdaQueryWrapper)) {
            keyPart2ensureIds.add(elem.getId());
        }
        // extension
        if (ensureStructurePageDTO.getExtensionId() != null) {
            LambdaQueryWrapper<FaEnsure> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FaEnsure::getIsSoftDelete, false);
            wrapper.eq(FaEnsure::getRaExtensionId, ensureStructurePageDTO.getExtensionId());
            for (FaEnsure elem : faEnsureMapper.selectList(wrapper)) {
                extension2ensureIds.add(elem.getId());
            }
        } else {
            LambdaQueryWrapper<FaEnsure> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(FaEnsure::getIsSoftDelete, false);
            wrapper1.eq(FaEnsure::getRaExtensionId, raTree.getExtensionId());
            for (FaEnsure elem : faEnsureMapper.selectList(wrapper1)) {
                extension2ensureIds.add(elem.getId());
            }
        }
        // system:
        if (ensureStructurePageDTO.getSystemId() != null) {
            LambdaQueryWrapper<FaEnsure> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FaEnsure::getIsSoftDelete, false);
            wrapper.eq(FaEnsure::getRaSystemId, ensureStructurePageDTO.getSystemId());
            for (FaEnsure elem : faEnsureMapper.selectList(wrapper)) {
                system2ensureIds.add(elem.getId());
            }
        } else {
            LambdaQueryWrapper<FaEnsure> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(FaEnsure::getIsSoftDelete, false);
            wrapper1.eq(FaEnsure::getRaSystemId, raTree.getSystemId());
            for (FaEnsure elem : faEnsureMapper.selectList(wrapper1)) {
                extension2ensureIds.add(elem.getId());
            }
        }
        //
        ensure2StructureVO.setStructureId(ensureStructurePageDTO.getStructureId());
        ensure2StructureVO.setExtension2ensureIds(extension2ensureIds);
        ensure2StructureVO.setKeyPart2ensureIds(keyPart2ensureIds);
        ensure2StructureVO.setSystem2ensureIds(system2ensureIds);
        return RootResponse.success(ensure2StructureVO);
    }

    @Override
    public RootResponse createStructure2EnsurePlan(CreateStructureEnsureDTO createStructureEnsureDTO, LoginUserDTO loginUserDTO) {

        if (!StringUtils.isEmpty(createStructureEnsureDTO.getEnsureBaseList())) {
            for (Ensure2EnsureTypeDTO ensure2ensureType : createStructureEnsureDTO.getEnsureBaseList()) {
                // delete
                for (String s1 : ensure2ensureType.getDeleteTypeIdList()) {
                    if (!StringUtils.isEmpty(s1) && !StringUtils.isEmpty(ensure2ensureType.getId()) && !StringUtils.isEmpty(createStructureEnsureDTO.getStructureId())) {
                        LambdaQueryWrapper<FaEnsurePlan> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(FaEnsurePlan::getEnsureTypeId, s1);
                        wrapper.eq(FaEnsurePlan::getEnsureId, ensure2ensureType.getId());
                        wrapper.eq(FaEnsurePlan::getStructureId, createStructureEnsureDTO.getStructureId());
                        //
                        List<FaEnsurePlan> faEnsurePlans = faEnsurePlanMapper.selectList(wrapper);
                        for (FaEnsurePlan faEnsurePlan : faEnsurePlans) { // 删除取消的时候判断是否再保障记录中存在
                            LambdaQueryWrapper<FaEnsureRecord> wrapper1 = new LambdaQueryWrapper<>();
                            wrapper1.eq(FaEnsureRecord::getPlanId, faEnsurePlan.getId());
                            wrapper1.eq(FaEnsureRecord::getIsSoftDelete, false);
                            List<FaEnsureRecord> isExistInRecord = faEnsureRecordMapper.selectList(wrapper1);
                            // 判断是否存在，是就不能删除。
                            if (isExistInRecord.size()>0){
                                return RootResponse.error("所选保障计划存在于保障记录中，不能被取消");
                            }
                        }
                        for (FaEnsurePlan faEnsurePlan : faEnsurePlans) { // 删除取消的时候判断是否再保障记录中存在
                            faEnsurePlan.setIsSoftDelete(true);
                            FaEnsurePlan faEnsurePlan1 = faEnsurePlan;
                            faEnsurePlanMapper.updateById(faEnsurePlan1);
                        }
                    }
                }
                // create
                for (String s : ensure2ensureType.getCreateTypeIdList()) {
                    var ensurePlan = new FaEnsurePlan();
                    ensurePlan.setId(HandleUtils.UUID32());
                    ensurePlan.setCreator(loginUserDTO.getUsername());
                    ensurePlan.setCreateDateTime(new Date());
                    ensurePlan.setIsSoftDelete(false);
                    ensurePlan.setEnsureId(ensure2ensureType.getId());
                    ensurePlan.setEnsureTypeId(s);
                    ensurePlan.setStatus(1);
                    //
                    ensurePlan.setStructureId(createStructureEnsureDTO.getStructureId());
                    // 添加之前判断是否有重复~
                    var wrapper = new LambdaQueryWrapper<FaEnsurePlan>();
                    wrapper.eq(FaEnsurePlan::getEnsureId, ensurePlan.getEnsureId());
                    wrapper.eq(FaEnsurePlan::getEnsureTypeId, ensurePlan.getEnsureTypeId());
                    wrapper.eq(FaEnsurePlan::getStructureId, ensurePlan.getStructureId());
                    wrapper.eq(FaEnsurePlan::getIsSoftDelete, false);
                    if (faEnsurePlanMapper.selectList(wrapper).size() > 0) {
                        return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障计划内容已存在，请勿重复添加");
                    }
                    int i = faEnsurePlanMapper.insert(ensurePlan);
                    if (i != 1) {
                        throw new RuntimeException("失败");
                    }
                }
            }
        }
        return RootResponse.success();
    }

    /**
     * @param faTaskLevelPageDTO:
     * @return
     */
    // select
    @Override
    public RootResponse<PageResult<FaTaskLevelVO>> queryFaTaskLevelPage(FaTaskLevelPageDTO faTaskLevelPageDTO) {
        var wrapper = new LambdaQueryWrapper<FaTaskLevel>();
        //
        wrapper.eq(FaTaskLevel::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (faTaskLevelPageDTO.getName() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaTaskLevel::getName, faTaskLevelPageDTO.getName());
        }
        //
        wrapper.orderByDesc(FaTaskLevel::getCreateDateTime, FaTaskLevel::getId);
        // page helper
        PageHelper.startPage(faTaskLevelPageDTO.getPageNum(), faTaskLevelPageDTO.getPageSize());
        var taskLevels = faTaskLevelMapper.selectList(wrapper);
        var pageInfo = PageInfo.of(taskLevels);
        var pageList = pageInfo.getList();
        System.out.println(pageList);//
        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
    }

    @Override
    public RootResponse createFaTaskLevel(CreateFaTaskLevelDTO createFaTaskLevelDTO, LoginUserDTO userDTO) {
        //
        var wrapper = new LambdaQueryWrapper<FaTaskLevel>();
        wrapper.eq(FaTaskLevel::getName, createFaTaskLevelDTO.getName());
        wrapper.eq(FaTaskLevel::getIsSoftDelete, false);
//        var faTaskLevel = faTaskLevelMapper.selectOne(wrapper);
        if (faTaskLevelMapper.selectOne(wrapper) != null) {
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "任务级别已存在，请勿重复添加");
        }
        //
        var faTaskLevel = new FaTaskLevel();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createFaTaskLevelDTO, faTaskLevel);
        faTaskLevel.setId(HandleUtils.UUID32());
        faTaskLevel.setCreator(userDTO.getUsername());
        faTaskLevel.setCreateDateTime(new Date());
        faTaskLevel.setIsSoftDelete(false);
        int i = faTaskLevelMapper.insert(faTaskLevel);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateFaTaskLevel(UpdateFaTaskLevelDTO updateFaTaskLevelDTO, LoginUserDTO userDTO) {
        var wrapper1 = new LambdaQueryWrapper<FaTaskLevel>();
        wrapper1.eq(FaTaskLevel::getName, updateFaTaskLevelDTO.getName());
        wrapper1.eq(FaTaskLevel::getIsSoftDelete, false);
        var faTaskLevel1 = faTaskLevelMapper.selectOne(wrapper1);
        if (faTaskLevel1 != null) {
            if (!faTaskLevel1.getId().equals(updateFaTaskLevelDTO.getId())) {
                //            var FaTaskLevel2 = baseMapper.selectOne(wrapper1);
                return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障名称已存在，请勿重复添加");

            }
        }
        // the old data:
        var faTaskLevel_old = faTaskLevelMapper.selectById(updateFaTaskLevelDTO.getId());
        var faTaskLevel = new FaTaskLevel();
        BeanCopyUtils.copy(updateFaTaskLevelDTO, faTaskLevel);
        faTaskLevel.setUpdater(userDTO.getUsername());
        faTaskLevel.setUpdateDateTime(new Date());
        int i = faTaskLevelMapper.updateById(faTaskLevel);
//        int i=1;
        return i == 1 ? RootResponse.success(faTaskLevel_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteFaTaskLevel(String id, LoginUserDTO userDTO) {
        // 判断是否被保障基础表关联，关联后不允许被删除喔！
        var ensureLambdaQueryWrapper = new LambdaQueryWrapper<FaEnsure>();
        ensureLambdaQueryWrapper.eq(FaEnsure::getIsSoftDelete, false);
        ensureLambdaQueryWrapper.eq(FaEnsure::getTaskLevelId, id);
        if (faEnsureMapper.selectList(ensureLambdaQueryWrapper).size() != 0) {
            return RootResponse.error("该级别已被保障基础信息绑定，不能删除");
        }
        //
        var wrapper = new LambdaQueryWrapper<FaTaskLevel>();
        wrapper.eq(FaTaskLevel::getId, id);
        wrapper.eq(FaTaskLevel::getIsSoftDelete, false);
        var faTaskLevel = faTaskLevelMapper.selectOne(wrapper);
        if (faTaskLevel == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faTaskLevel.setIsSoftDelete(true);
        faTaskLevel.setUpdateDateTime(new Date());
        faTaskLevel.setUpdater(userDTO.getUsername());
        faTaskLevelMapper.updateById(faTaskLevel);
        return RootResponse.success(faTaskLevelMapper.selectById(id));
    }


    @Override
    public RootResponse<PageResult<List<FaEnsureTypeVO>>> queryFaEnsureTypePage(EnsureTypePageDTO faEnsureTypePageDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsureType>();
        List<FaEnsureTypeVO> faEnsureTypeVOList = new ArrayList<>();
        //
        wrapper.eq(FaEnsureType::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (faEnsureTypePageDTO.getName() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaEnsureType::getName, faEnsureTypePageDTO.getName());
        }
        //
        wrapper.orderByDesc(FaEnsureType::getCreateDateTime, FaEnsureType::getId);
        // page helper
        var faEnsureTypes = faEnsureTypeMapper.selectList(wrapper);
        PageHelper.startPage(faEnsureTypePageDTO.getPageNum(), faEnsureTypePageDTO.getPageSize());
        if ("00".equals(faEnsureTypePageDTO.getNoRecursion())) {// 00 表示是否递归查询
            if ("00".equals(faEnsureTypePageDTO.getType())) { // 00 表示是否分页查询
                if (faEnsureTypePageDTO.getName() != null && !faEnsureTypePageDTO.getName().equals("")) {// 查询条件是否含名称进行模糊查询
                    for (FaEnsureType ensureType : faEnsureTypes) {
                        if (StringUtils.isEmpty(ensureType.getParentId()) && ensureType.getName().contains(faEnsureTypePageDTO.getName())) {
                            FaEnsureTypeVO faEnsureTypeVO = new FaEnsureTypeVO();
                            faEnsureTypeVO.setId(ensureType.getId());
                            faEnsureTypeVO.setName(ensureType.getName());
                            faEnsureTypeVO.setRemarks(ensureType.getRemarks());
                            faEnsureTypeVO.setDescription(ensureType.getDescription());
                            faEnsureTypeVO.setCycle(ensureType.getCycle());
                            faEnsureTypeVOList.add(faEnsureTypeVO);

                        }
                    }
                    return RootResponse.success(faEnsureTypeVOList);
                } else {
                    for (FaEnsureType ensureType : faEnsureTypes) {
                        if (StringUtils.isEmpty(ensureType.getParentId())) {
                            FaEnsureTypeVO faEnsureTypeVO = new FaEnsureTypeVO();
                            faEnsureTypeVO.setId(ensureType.getId());
                            faEnsureTypeVO.setName(ensureType.getName());
                            faEnsureTypeVO.setRemarks(ensureType.getRemarks());
                            faEnsureTypeVO.setDescription(ensureType.getDescription());
                            faEnsureTypeVO.setCycle(ensureType.getCycle());
                            faEnsureTypeVOList.add(faEnsureTypeVO);

                        }
                    }
                    return RootResponse.success(faEnsureTypeVOList);
                }
            } else {
                if (faEnsureTypePageDTO.getName() != null && !faEnsureTypePageDTO.getName().equals("")) {
                    for (FaEnsureType ensureType : faEnsureTypes) {
                        if (StringUtils.isEmpty(ensureType.getParentId())
                                && ensureType.getName().contains(faEnsureTypePageDTO.getName())
                        ) {
                            FaEnsureTypeVO faEnsureTypeVO = new FaEnsureTypeVO();
                            faEnsureTypeVO.setId(ensureType.getId());
                            faEnsureTypeVO.setName(ensureType.getName());
                            faEnsureTypeVO.setRemarks(ensureType.getRemarks());
                            faEnsureTypeVO.setDescription(ensureType.getDescription());
                            faEnsureTypeVO.setCycle(ensureType.getCycle());
                            faEnsureTypeVOList.add(faEnsureTypeVO);
                        }
                    }
                    var pageInfo = PageInfo.of(faEnsureTypeVOList);
                    var pageList = pageInfo.getList();
                    System.out.println(pageList);//
                    return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
                } else {
                    for (FaEnsureType ensureType : faEnsureTypes) {
                        if (StringUtils.isEmpty(ensureType.getParentId())) {
                            FaEnsureTypeVO faEnsureTypeVO = new FaEnsureTypeVO();
                            faEnsureTypeVO.setId(ensureType.getId());
                            faEnsureTypeVO.setName(ensureType.getName());
                            faEnsureTypeVO.setRemarks(ensureType.getRemarks());
                            faEnsureTypeVO.setDescription(ensureType.getDescription());
                            faEnsureTypeVO.setCycle(ensureType.getCycle());
                            faEnsureTypeVOList.add(faEnsureTypeVO);
                        }
                    }
                    var pageInfo = PageInfo.of(faEnsureTypeVOList);
                    var pageList = pageInfo.getList();
                    System.out.println(pageList);//
                    return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
                }
            }
        } else {
            // 这里是选择递归查询：
            if ("00".equals(faEnsureTypePageDTO.getType())) {
                if (faEnsureTypePageDTO.getName() != null && !faEnsureTypePageDTO.getName().equals("")) { // 查询name用
                    List<FaEnsureTypeVO> ensureTypeAll = new ArrayList<>();
                    for (FaEnsureType elem : faEnsureTypes) {
                        //
                        if (elem.getName().contains(faEnsureTypePageDTO.getName())) {
                            FaEnsureTypeVO ensureTypeVO = new FaEnsureTypeVO();
                            ensureTypeVO.setId(elem.getId());
                            ensureTypeVO.setName(elem.getName());
                            ensureTypeVO.setDescription(elem.getDescription());
                            ensureTypeVO.setParentId(elem.getParentId());
                            ensureTypeVO.setRemarks(elem.getRemarks());
                            ensureTypeVO.setCycle(elem.getCycle());
                            ensureTypeAll.add(ensureTypeVO);
                        }
                    }
                    // 一级list
                    List<FaEnsureTypeVO> ensureTypeVOS = new ArrayList<>();
                    for (FaEnsureTypeVO elem : ensureTypeAll) {
                        if (StringUtils.isEmpty(elem.getParentId())) {
                            //
                            ensureTypeVOS.add(elem);
                        }
                    }
                    for (FaEnsureTypeVO elem : ensureTypeVOS) {
                        elem.setResList(recursionEnsureTypeWithName(elem.getId(), ensureTypeAll, faEnsureTypePageDTO.getName()));
                    }
                    if (faEnsureTypePageDTO.getName() != null && !faEnsureTypePageDTO.getName().equals("")) {
                        // 有名称查询的时候,直接返回所有名称匹配的数据，无需递归
                        // 将所有的id存为结果ids，用于判断其是否含有父级菜单;
                        List<String> ensureTypeIds = new ArrayList<>();
                        for (FaEnsureTypeVO typeVO : ensureTypeAll) {
                            ensureTypeIds.add(typeVO.getId());
                        }
                        for (FaEnsureTypeVO typeVO : ensureTypeAll) {
                            if (!StringUtils.isEmpty(typeVO.getParentId()) && ensureTypeIds.contains(typeVO.getParentId())) {
                                ensureTypeAll.remove(typeVO);
                            }
                        }
                        return RootResponse.success(ensureTypeAll);// 有名称查询的时候
                    } else {
                        return RootResponse.success(ensureTypeVOS);
                    }
                } else {
                    List<FaEnsureTypeVO> ensureTypeAll = new ArrayList<>();
                    for (FaEnsureType elem : faEnsureTypes) {
                        FaEnsureTypeVO ensureTypeVO = new FaEnsureTypeVO();
                        ensureTypeVO.setId(elem.getId());
                        ensureTypeVO.setName(elem.getName());
                        ensureTypeVO.setDescription(elem.getDescription());
                        ensureTypeVO.setParentId(elem.getParentId());
                        ensureTypeVO.setRemarks(elem.getRemarks());
                        ensureTypeVO.setCycle(elem.getCycle());
                        //
                        ensureTypeAll.add(ensureTypeVO);
                    }
                    // 一级list
                    List<FaEnsureTypeVO> ensureTypeVOS = new ArrayList<>();
                    for (FaEnsureTypeVO elem : ensureTypeAll) {
                        if (StringUtils.isEmpty(elem.getParentId())) {
                            //
                            ensureTypeVOS.add(elem);
                        }
                    }
                    for (FaEnsureTypeVO elem : ensureTypeVOS) {
                        elem.setResList(recursionEnsureType(elem.getId(), ensureTypeAll));
                    }
                    return RootResponse.success(ensureTypeVOS);
                }

            } else { // 表示进行分页查询
                if (faEnsureTypePageDTO.getName() != null && !faEnsureTypePageDTO.getName().equals("")) {
                    List<FaEnsureTypeVO> ensureTypeAll = new ArrayList<>();
                    for (FaEnsureType elem : faEnsureTypes) {
                        if (elem.getName().contains(faEnsureTypePageDTO.getName())) {
                            FaEnsureTypeVO ensureTypeVO = new FaEnsureTypeVO();
                            ensureTypeVO.setId(elem.getId());
                            ensureTypeVO.setName(elem.getName());
                            ensureTypeVO.setDescription(elem.getDescription());
                            ensureTypeVO.setParentId(elem.getParentId());
                            ensureTypeVO.setRemarks(elem.getRemarks());
                            ensureTypeVO.setCycle(elem.getCycle());
                            //
                            ensureTypeAll.add(ensureTypeVO);
                        }
                    }
                    // 一级list
                    List<FaEnsureTypeVO> ensureTypeVOS = new ArrayList<>();
                    for (FaEnsureTypeVO elem : ensureTypeAll) {// 从所有的匹配name的进行结果集封装
                        if (StringUtils.isEmpty(elem.getParentId())) {
                            //
                            ensureTypeVOS.add(elem);
                        }
                    }
                    for (FaEnsureTypeVO elem : ensureTypeVOS) {
                        elem.setResList(recursionEnsureTypeWithName(elem.getId(), ensureTypeAll, faEnsureTypePageDTO.getName()));
                    }
                    if (faEnsureTypePageDTO.getName() != null && !faEnsureTypePageDTO.getName().equals("")) {
                        // 有名称查询的时候,直接返回所有名称匹配的数据，无需递归
                        // 将所有的id存为结果ids，用于判断其是否含有父级菜单;
                        List<String> ensureTypeIds = new ArrayList<>();
                        for (FaEnsureTypeVO typeVO : ensureTypeAll) {
                            ensureTypeIds.add(typeVO.getId());
                        }
                        for (FaEnsureTypeVO typeVO : ensureTypeAll) {
                            if (!StringUtils.isEmpty(typeVO.getParentId()) && ensureTypeIds.contains(typeVO.getParentId())) {
                                ensureTypeAll.remove(typeVO);
                            }
                        }
                        var pageInfo = PageInfo.of(ensureTypeAll);
                        var pageList = pageInfo.getList();
                        System.out.println(pageList);//
                        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
                    } else {
                        var pageInfo = PageInfo.of(ensureTypeVOS);
                        var pageList = pageInfo.getList();
                        System.out.println(pageList);//
                        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
                    }
                } else {
                    List<FaEnsureTypeVO> ensureTypeAll = new ArrayList<>();
                    for (FaEnsureType elem : faEnsureTypes) {
                        FaEnsureTypeVO ensureTypeVO = new FaEnsureTypeVO();
                        ensureTypeVO.setId(elem.getId());
                        ensureTypeVO.setName(elem.getName());
                        ensureTypeVO.setDescription(elem.getDescription());
                        ensureTypeVO.setParentId(elem.getParentId());
                        ensureTypeVO.setRemarks(elem.getRemarks());
                        ensureTypeVO.setCycle(elem.getCycle());
                        //
                        ensureTypeAll.add(ensureTypeVO);
                    }
                    // 一级list
                    List<FaEnsureTypeVO> ensureTypeVOS = new ArrayList<>();
                    for (FaEnsureTypeVO elem : ensureTypeAll) {
                        if (StringUtils.isEmpty(elem.getParentId())) {
                            //
                            ensureTypeVOS.add(elem);
                        }
                    }
                    for (FaEnsureTypeVO elem : ensureTypeVOS) {
                        elem.setResList(recursionEnsureType(elem.getId(), ensureTypeAll));
                    }
                    var pageInfo = PageInfo.of(ensureTypeVOS);
                    var pageList = pageInfo.getList();
                    System.out.println(pageList);//
                    return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));

                }

            }
        }
    }

    // 递归查询子列表(含名字查询匹配)
    @Override
    public List<FaEnsureTypeVO> recursionEnsureTypeWithName(String id, List<FaEnsureTypeVO> faEnsureTypeVOS, String queryName) {
        List<FaEnsureTypeVO> child = new ArrayList<>();
        for (FaEnsureTypeVO ensureTypeVO : faEnsureTypeVOS) {
            if (ensureTypeVO.getParentId() != null && ensureTypeVO.getParentId().equals(id)
                    && ensureTypeVO.getName().contains(queryName)) {// 实现名称的模糊匹配查询
                for (FaEnsureTypeVO temp : faEnsureTypeVOS) {
                    if (temp.getId().equals(id)) {
                        ensureTypeVO.setParentName(temp.getName());
                        break;
                    }
                }
                child.add(ensureTypeVO);
            }
        }
        // recursion:
        for (FaEnsureTypeVO ensureTypeVO : child) {
            ensureTypeVO.setResList(recursionEnsureTypeWithName(ensureTypeVO.getId(),
                    faEnsureTypeVOS, queryName));
        }
        // return
        if (child.size() == 0) {
            return null;
        }
        return child;
    }

    // 递归查询子列表(不含名字查询匹配)
    @Override
    public List<FaEnsureTypeVO> recursionEnsureType(String id, List<FaEnsureTypeVO> faEnsureTypeVOS) {
        List<FaEnsureTypeVO> child = new ArrayList<>();
        for (FaEnsureTypeVO ensureTypeVO : faEnsureTypeVOS) {
            if (ensureTypeVO.getParentId() != null && ensureTypeVO.getParentId().equals(id)) {
                for (FaEnsureTypeVO temp : faEnsureTypeVOS) {
                    if (temp.getId().equals(id)) {
                        ensureTypeVO.setParentName(temp.getName());
                        break;
                    }
                }
                child.add(ensureTypeVO);
            }
        }
        // recursion:
        for (FaEnsureTypeVO ensureTypeVO : child) {
            ensureTypeVO.setResList(recursionEnsureType(ensureTypeVO.getId(),
                    faEnsureTypeVOS));
        }
        // return
        if (child.size() == 0) {
            return null;
        }
        return child;
    }

    @Override
    public RootResponse createFaEnsureType(CreateEnsureTypeDTO createFaEnsureTypeDTO, LoginUserDTO userDTO) {
        //
        var wrapper = new LambdaQueryWrapper<FaEnsureType>();
        wrapper.eq(FaEnsureType::getName, createFaEnsureTypeDTO.getName());
        wrapper.eq(FaEnsureType::getIsSoftDelete, false);
//        var faEnsureType = faEnsureTypeMapper.selectOne(wrapper);
        if (faEnsureTypeMapper.selectOne(wrapper) != null) {
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障类型已存在，请勿重复添加");
        }
        //
        var faEnsureType = new FaEnsureType();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createFaEnsureTypeDTO, faEnsureType);
        faEnsureType.setId(HandleUtils.UUID32());
        faEnsureType.setCreator(userDTO.getUsername());
        faEnsureType.setCreateDateTime(new Date());
        faEnsureType.setIsSoftDelete(false);
        int i = faEnsureTypeMapper.insert(faEnsureType);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateFaEnsureType(UpdateEnsureTypeDTO updateFaEnsureTypeDTO, LoginUserDTO userDTO) {
        var wrapper1 = new LambdaQueryWrapper<FaEnsureType>();
        wrapper1.eq(FaEnsureType::getName, updateFaEnsureTypeDTO.getName());
        wrapper1.eq(FaEnsureType::getIsSoftDelete, false);
        var faEnsureType1 = faEnsureTypeMapper.selectOne(wrapper1);
        if (faEnsureType1 != null) {
            if (!faEnsureType1.getId().equals(updateFaEnsureTypeDTO.getId())) {
                //            var FaEnsureType2 = baseMapper.selectOne(wrapper1);
                return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障类型已存在，请勿重复添加");

            }
        }
        // the old data:
        var faEnsureType_old = faEnsureTypeMapper.selectById(updateFaEnsureTypeDTO.getId());
        var faEnsureType = new FaEnsureType();
        BeanCopyUtils.copy(updateFaEnsureTypeDTO, faEnsureType);
        faEnsureType.setUpdater(userDTO.getUsername());
        faEnsureType.setUpdateDateTime(new Date());
        int i = faEnsureTypeMapper.updateById(faEnsureType);
//        int i=1;
        return i == 1 ? RootResponse.success(faEnsureType_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteFaEnsureType(String id, LoginUserDTO userDTO) {
        // 判断其是不是父级，如果是，有没有子集，有不能删除。
        LambdaQueryWrapper<FaEnsureType> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(FaEnsureType::getIsSoftDelete, false);
        wrapper1.eq(FaEnsureType::getId, id);
        FaEnsureType ensureType = faEnsureTypeMapper.selectOne(wrapper1);
        if (ensureType != null && StringUtils.isEmpty(ensureType.getParentId())) {
            LambdaQueryWrapper<FaEnsureType> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(FaEnsureType::getIsSoftDelete, false);
            wrapper2.eq(FaEnsureType::getParentId, id);
            List<FaEnsureType> faEnsureTypes = faEnsureTypeMapper.selectList(wrapper2);
            if (faEnsureTypes.size() > 0) {
                return RootResponse.error("该父类型存在子类型，不能删除");
            }
        }
        // 判断是否被保障基础表关联，关联后不允许被删除喔！
        var ensureLambdaQueryWrapper = new LambdaQueryWrapper<FaEnsurePlan>();
        ensureLambdaQueryWrapper.eq(FaEnsurePlan::getIsSoftDelete, false);
        ensureLambdaQueryWrapper.eq(FaEnsurePlan::getEnsureTypeId, id);
        if (faEnsurePlanMapper.selectList(ensureLambdaQueryWrapper).size() > 0) {
            return RootResponse.error("该类型已存在于保障计划，不能删除");
        }
        //
        var wrapper = new LambdaQueryWrapper<FaEnsureType>();
        wrapper.eq(FaEnsureType::getId, id);
        wrapper.eq(FaEnsureType::getIsSoftDelete, false);
        var faEnsureType = faEnsureTypeMapper.selectOne(wrapper);
        if (faEnsureType == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faEnsureType.setIsSoftDelete(true);
        faEnsureType.setUpdateDateTime(new Date());
        faEnsureType.setUpdater(userDTO.getUsername());
        faEnsureTypeMapper.updateById(faEnsureType);
        return RootResponse.success(faEnsureTypeMapper.selectById(id));
    }


    /**
     * @param ensurePageDTO:
     * @return
     */
    @Override
    public RootResponse<PageResult<FaEnsureVO>> queryFaEnsurePage(EnsurePageDTO ensurePageDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsure>();
        wrapper.eq(FaEnsure::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (ensurePageDTO.getName() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaEnsure::getName, ensurePageDTO.getName());
        }
        //
        wrapper.orderByDesc(FaEnsure::getCreateDateTime, FaEnsure::getId);
        // page helper
        PageHelper.startPage(ensurePageDTO.getPageNum(), ensurePageDTO.getPageSize());
        var ensures = faEnsureMapper.selectFaEnsure(ensurePageDTO);
        // 查询的时候如果有一下条件：
        if (!StringUtils.isEmpty(ensurePageDTO.getRaSystemId()) || !StringUtils.isEmpty(ensurePageDTO.getKeyPartsModelId()) || !StringUtils.isEmpty(ensurePageDTO.getRaExtensionId())) {
            List<FaEnsureVO> accuracyFindRes = new ArrayList<>();
            ensures.forEach(
                    elem -> {
                        // 注意层级关系
                        if (!StringUtils.isEmpty(ensurePageDTO.getRaSystemId()) && !StringUtils.isEmpty(ensurePageDTO.getKeyPartsModelId()) && !StringUtils.isEmpty(ensurePageDTO.getRaExtensionId())) {
                            if (ensurePageDTO.getRaSystemId().equals(elem.getRaSystemId()) && elem.getRaExtensionId().equals(ensurePageDTO.getRaExtensionId()) && elem.getKeyPartsModelId().equals(ensurePageDTO.getKeyPartsModelId())) {
                                accuracyFindRes.add(elem);
                            }
                        }
                        if (!StringUtils.isEmpty(ensurePageDTO.getRaSystemId()) && StringUtils.isEmpty(ensurePageDTO.getKeyPartsModelId()) && !StringUtils.isEmpty(ensurePageDTO.getRaExtensionId())) {
                            if (ensurePageDTO.getRaSystemId().equals(elem.getRaSystemId()) && elem.getRaExtensionId().equals(ensurePageDTO.getRaExtensionId()) && StringUtils.isEmpty(elem.getKeyPartsModelId())) {
                                accuracyFindRes.add(elem);
                            }
                        }
                        if (!StringUtils.isEmpty(ensurePageDTO.getRaSystemId()) && StringUtils.isEmpty(ensurePageDTO.getKeyPartsModelId()) && StringUtils.isEmpty(ensurePageDTO.getRaExtensionId())) {
                            if (ensurePageDTO.getRaSystemId().equals(elem.getRaSystemId()) && StringUtils.isEmpty(elem.getRaExtensionId()) && StringUtils.isEmpty(elem.getKeyPartsModelId())) {
                                accuracyFindRes.add(elem);
                            }
                        }
                    }
            );
            var pageInfo = PageInfo.of(accuracyFindRes);
            var pageList = pageInfo.getList();
            pageList.forEach(p->{
                String a=p.getKeyPartsModelTypeName()!=null?p.getKeyPartsModelTypeName():"";
                a+=p.getKeyPartsModelName()!=null?p.getKeyPartsModelName():"";
                p.setKeyPartsModelName(a);
            });
            return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
        }
        var pageInfo = PageInfo.of(ensures);
        var pageList = pageInfo.getList();
        pageList.forEach(p->{
            String a=p.getKeyPartsModelTypeName()!=null?p.getKeyPartsModelTypeName():"";
            a+=p.getKeyPartsModelName()!=null?p.getKeyPartsModelName():"";
            p.setKeyPartsModelName(a);
        });
        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
    }

    @Override
    public RootResponse createEnsure(CreateEnsureDTO createEnsureDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsure>();
        // 查重：
        wrapper.eq(FaEnsure::getName, createEnsureDTO.getName());
        wrapper.eq(FaEnsure::getIsSoftDelete, false);
        var faEnsure1 = faEnsureMapper.selectOne(wrapper);
        if (faEnsure1 != null) {
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障基础已存在，请勿重复添加");
        }
        //
        var faEnsure = new FaEnsure();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createEnsureDTO, faEnsure);
        faEnsure.setId(HandleUtils.UUID32());
        faEnsure.setCreator(userDTO.getUsername());
        faEnsure.setCreateDateTime(new Date());
        faEnsure.setIsSoftDelete(false);
        int i = faEnsureMapper.insert(faEnsure);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateEnsure(UpdateEnsureDTO updateEnsureDTO, LoginUserDTO userDTO) {
        var wrapper1 = new LambdaQueryWrapper<FaEnsure>();
        wrapper1.eq(FaEnsure::getName, updateEnsureDTO.getName());
        wrapper1.eq(FaEnsure::getIsSoftDelete, false);
        var faEnsure1 = faEnsureMapper.selectOne(wrapper1);
        //
        if (faEnsure1 != null) {
            if (!faEnsure1.getId().equals(updateEnsureDTO.getId())) {
//            var FaTaskLevel2 = baseMapper.selectOne(wrapper1);
                return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障已存在，请勿重复添加");

            }
        }

        // the old data:
        var faEnsure_old = faEnsureMapper.selectById(updateEnsureDTO.getId());
        var faEnsure = new FaEnsure();
        BeanCopyUtils.copy(updateEnsureDTO, faEnsure);
        faEnsure.setUpdater(userDTO.getUsername());
        faEnsure.setUpdateDateTime(new Date());
        int i = faEnsureMapper.updateById(faEnsure);
        return i == 1 ? RootResponse.success(faEnsure_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteEnsure(String ensureId, LoginUserDTO userDTO) {
        // 判断是否在保养记录中存在，如果存在不能删除
        LambdaQueryWrapper<FaEnsurePlan> faEnsurePlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        faEnsurePlanLambdaQueryWrapper.eq(FaEnsurePlan::getIsSoftDelete, false);
        faEnsurePlanLambdaQueryWrapper.eq(FaEnsurePlan::getEnsureId, ensureId);
        if (faEnsurePlanMapper.selectList(faEnsurePlanLambdaQueryWrapper).size() > 0) {
            return RootResponse.error("该保障基础信息在保养或保障记录中存在！！！");
        }

        var faEnsure_old = faEnsureMapper.selectById(ensureId);
        var queryWrapper = new LambdaQueryWrapper<FaEnsure>();
        queryWrapper.eq(FaEnsure::getId, ensureId);
        queryWrapper.eq(FaEnsure::getIsSoftDelete, false);
        var faEnsure = faEnsureMapper.selectOne(queryWrapper);
        if (faEnsure == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faEnsure.setIsSoftDelete(true);
        faEnsure.setUpdateDateTime(new Date());
        faEnsure.setUpdater(userDTO.getUsername());
        faEnsureMapper.updateById(faEnsure);
        return RootResponse.success(faEnsure_old);
    }


    /**
     * @param ensurePlanDTO:
     * @return
     */
    @Override
    public RootResponse<PageResult<FaEnsurePlanVO>> queryFaEnsurePlanPage(EnsurePlanDTO ensurePlanDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsurePlan>();
//        var fpVO = new FaEnsurePlanVO();
        wrapper.eq(FaEnsurePlan::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (ensurePlanDTO.getId() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaEnsurePlan::getId, ensurePlanDTO.getId());
        }
        //
        wrapper.orderByDesc(FaEnsurePlan::getCreateDateTime);
        // page helper
        var faEnsurePlanVOS_pre = faEnsurePlanMapper.selectEnsurePlan(ensurePlanDTO);

        List<FaEnsurePlanVO> pageList;
        if (!StringUtils.isEmpty(userDTO.getAreaId())) {
            List<FaEnsurePlanVO> faEnsurePlanVOS = new ArrayList<>();
            if (!StringUtils.isEmpty(userDTO.getAreaId())) {
                for (FaEnsurePlanVO ensurePlanVO : faEnsurePlanVOS_pre) {
                    if (!StringUtils.isEmpty(ensurePlanVO.getStructureId())) {
                        if (raRadarMapper.selectById(raTreeMapper.selectById(ensurePlanVO.getStructureId()).getRadarId()) != null) {
                            String areaId = raStationMapper.selectById(raRadarMapper.selectById(raTreeMapper.selectById(faEnsurePlanMapper.selectById(ensurePlanVO.getId()).getStructureId()).getRadarId()).getSiteId()).getAreaId();
                            if (areaId.equals(userDTO.getAreaId())) {
                                faEnsurePlanVOS.add(ensurePlanVO);
                            }// 如果不是这个区域的就删除。
                        }
                    }
                }
            }
            pageList = faEnsurePlanVOS;
        } else {
            pageList = faEnsurePlanVOS_pre;
        }
        List<FaEnsurePlanVO> faEnsurePlanVOList0 = new ArrayList<>(); // query by Urgent;
        List<FaEnsurePlanVO> faEnsurePlanVOList1 = new ArrayList<>(); // query by Urgent;
        List<FaEnsurePlanVO> faEnsurePlanVOList2 = new ArrayList<>(); // query by Urgent;
        List<FaEnsurePlanVO> faEnsurePlanVOList = new ArrayList<>(); // query by Urgent;
        pageList.forEach(elem -> {
            // add the extension and the system;
            if (elem.getStructureId() != null) {
                if (raTreeMapper.selectById(elem.getStructureId()).getExtensionId() != null) {
                    String extensionId = raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getId()).getStructureId()).getExtensionId();
                    String extensionName = raExtensionMapper.selectById(extensionId).getName();
                    elem.setExtensionName(extensionName);
                    elem.setExtensionId(extensionId);
                }
                if (raTreeMapper.selectById(elem.getStructureId()).getSystemId() != null) {
                    String systemId = raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getId()).getStructureId()).getSystemId();
                    String systemName = raSystemMapper.selectById(systemId).getName();
                    elem.setSystemName(systemName);
                    elem.setSystemId(systemId);
                }
                if (raTreeMapper.selectById(elem.getStructureId()).getKeyPartsModelId() != null) {
                    String keyPartsModelId = raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getId()).getStructureId()).getKeyPartsModelId();
                   var raKeyPartsModel= raKeyPartsModelMapper.selectById(keyPartsModelId);
                    String keyPartsModelName = raKeyPartsTypeMapper.selectById(raKeyPartsModel.getTypeId()).getName()+raKeyPartsModel.getName();
                    elem.setKeyPartsModelName(keyPartsModelName);
//                    elem.setk(keyPartsModelId);
                }
            }
            // add the cycle and radarName, key parts model name;
            if (raRadarMapper.selectById(raTreeMapper.selectById(elem.getStructureId()).getRadarId()) != null) {
                String radarName = raRadarMapper.selectById(raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getId()).getStructureId()).getRadarId()).getName();
                elem.setRadarName(radarName);
            }
            if (faEnsureTypeMapper.selectById(elem.getEnsureTypeId()) != null) {
                String cycle = "" + faEnsureTypeMapper.selectById(elem.getEnsureTypeId()).getCycle();
                elem.setCycle(cycle);
            }
            // is urgent:
            Date ensureDate = elem.getEnsureDate();// time;is null?
            Date now = new Date();
            // format:
            var df = new SimpleDateFormat("yyyy-MM-dd");
            // ensure id;
            var faEnsureType = faEnsureTypeMapper.selectById(elem.getEnsureTypeId());
            var faEnsureCycle = faEnsureType.getCycle(); // seconds;
            if (faEnsureCycle > 0) { // 保障类型周期存在，
                double calc_time = 0.0;
                //
                if (ensureDate != null) {// 存在保障时间
                    ensureDate = elem.getEnsureDate();
                    calc_time = (((Double.valueOf(ensureDate.getTime() / 1000 + faEnsureCycle) - now.getTime() / 1000) / 60) / 60) / 24;
                    if (calc_time <= Double.valueOf(1)) {
                        elem.setIsUrgent(2);
                    } else if (Double.valueOf(1) < calc_time && calc_time <= Double.valueOf(2)) {
                        elem.setIsUrgent(1);
                    } else {
                        elem.setIsUrgent(0);
                    }
                } else {
                    ensureDate = faEnsurePlanMapper.selectById(elem.getId()).getCreateDateTime();
                    calc_time = (((Double.valueOf(ensureDate.getTime() / 1000 + faEnsureCycle) - now.getTime() / 1000) / 60) / 60) / 24;
                    if (calc_time <= Double.valueOf(1)) {
                        elem.setIsUrgent(2);
                    } else if (Double.valueOf(1) < calc_time && calc_time <= Double.valueOf(2)) {
                        elem.setIsUrgent(1);
                    } else {
                        elem.setIsUrgent(0);
                    }
                }
            } else {
                elem.setIsUrgent(-1);
            }
        });
//        System.out.println(pageList);
        pageList.forEach(elem -> {
            if (!StringUtils.isEmpty(ensurePlanDTO.getIsUrgent())) {
                if (ensurePlanDTO.getIsUrgent().equals("0") && elem.getIsUrgent() == 0) {// 0:
                    faEnsurePlanVOList0.add(elem);
                }
                if (ensurePlanDTO.getIsUrgent().equals("1") && elem.getIsUrgent() == 1) {// 1:
                    faEnsurePlanVOList1.add(elem);
                }
                if (ensurePlanDTO.getIsUrgent().equals("2") && elem.getIsUrgent() == 2) {// 2:
                    faEnsurePlanVOList2.add(elem);
                }
            }
        });
        // isUrgent 分类；
        if (!StringUtils.isEmpty(ensurePlanDTO.getIsUrgent())) {
            if (ensurePlanDTO.getIsUrgent().equals("0")) {// 0:
                faEnsurePlanVOList.addAll(faEnsurePlanVOList0);

            }
            if (ensurePlanDTO.getIsUrgent().equals("1")) {// 1:
                faEnsurePlanVOList.addAll(faEnsurePlanVOList1);

            }
            if (ensurePlanDTO.getIsUrgent().equals("2")) {// 2:
                faEnsurePlanVOList.addAll(faEnsurePlanVOList2);

            }
        } else {
            faEnsurePlanVOList.addAll(pageList);

        }
        return RootResponse.success(PagingResultUtils.getPagingResultMap(faEnsurePlanVOList, ensurePlanDTO.getPageNum(), ensurePlanDTO.getPageSize()));


    }

    @Override
    public RootResponse createEnsurePlan(CreateEnsurePlanDTO createEnsurePlanDTO, LoginUserDTO userDTO) {
//        //
        var wrapper = new LambdaQueryWrapper<FaEnsurePlan>();
        wrapper.eq(FaEnsurePlan::getEnsureId, createEnsurePlanDTO.getEnsureId());
        wrapper.eq(FaEnsurePlan::getEnsureTypeId, createEnsurePlanDTO.getEnsureTypeId());
        wrapper.eq(FaEnsurePlan::getStructureId, createEnsurePlanDTO.getStructureId());
        wrapper.eq(FaEnsurePlan::getIsSoftDelete, false);

        if (faEnsurePlanMapper.selectList(wrapper).size() > 0) {
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障计划内容已存在，请勿重复添加");
        }
//        //

        var faEnsurePlan = new FaEnsurePlan();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createEnsurePlanDTO, faEnsurePlan);
//        var faEnsureRecord = faEnsureRecordMapper.selectById(faEnsurePlan.getEnsureRecordId());
//        // get the latest update time;
//        faEnsurePlan.setEnsureRecordLatestTime(faEnsureRecord.getCreateDateTime());
        faEnsurePlan.setId(HandleUtils.UUID32());
        faEnsurePlan.setCreator(userDTO.getUsername());
        faEnsurePlan.setCreateDateTime(new Date());
        faEnsurePlan.setIsSoftDelete(false);
//        // set date:
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String str = createEnsurePlanDTO.getEnsureDate();
//        Date date = null;
//        try {
//            date = dateFormat.parse(str);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        faEnsurePlan.setEnsureDate(createEnsurePlanDTO.getEnsureDate());
//        int i = faEnsurePlanMapper.insert(faEnsurePlan);
        var faEnsureRecord = new FaEnsureRecord();
        faEnsureRecord.setUser(userDTO.getUsername());
        faEnsureRecord.setId(HandleUtils.UUID32());
        faEnsureRecord.setCreator(userDTO.getUsername());
        faEnsureRecord.setCreateDateTime(new Date());
        faEnsureRecord.setPlanId(createEnsurePlanDTO.getId());
        faEnsureRecord.setDocumentationId(createEnsurePlanDTO.getDocumentationId());
        faEnsureRecord.setWayId(createEnsurePlanDTO.getWayId());
        faEnsureRecord.setEnsureDate(faEnsurePlan.getEnsureDate());
        faEnsureRecord.setIsSoftDelete(false);
        int i = faEnsureRecordMapper.insert(faEnsureRecord);
        if (i != 0) {
//            var faEnsurePlan_old = faEnsurePlanMapper.selectById(createEnsurePlanDTO.getId());
            var faEnsurePlanUpdate = new FaEnsurePlan();
            BeanCopyUtils.copy(createEnsurePlanDTO, faEnsurePlanUpdate);
            faEnsurePlanUpdate.setUpdater(userDTO.getUsername());
            faEnsurePlanUpdate.setUpdateDateTime(new Date());
            // set date:
//            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
////            dateFormat1.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//            String str1 = createEnsurePlanDTO.getEnsureDate();
//            Date date1 = null;
//            try {
//                date1 = dateFormat1.parse(str1);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
            faEnsurePlanUpdate.setEnsureDate(createEnsurePlanDTO.getEnsureDate());
            faEnsurePlanMapper.updateById(faEnsurePlanUpdate);
        }
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateEnsurePlan(UpdateEnsurePlanDTO updateEnsurePlanDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsurePlan>();
        wrapper.eq(FaEnsurePlan::getEnsureId, updateEnsurePlanDTO.getEnsureId());
        wrapper.eq(FaEnsurePlan::getEnsureTypeId, updateEnsurePlanDTO.getEnsureTypeId());
        wrapper.eq(FaEnsurePlan::getStructureId, updateEnsurePlanDTO.getStructureId());
        wrapper.eq(FaEnsurePlan::getIsSoftDelete, false);

        if (faEnsurePlanMapper.selectList(wrapper).size() > 0) {
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障计划内容已存在，请勿重复添加");
        }
        // the old data:
        var faEnsurePlan_old = faEnsurePlanMapper.selectById(updateEnsurePlanDTO.getId());
        var faEnsurePlan = new FaEnsurePlan();
        BeanCopyUtils.copy(updateEnsurePlanDTO, faEnsurePlan);
        faEnsurePlan.setUpdater(userDTO.getUsername());
        faEnsurePlan.setUpdateDateTime(new Date());
        // set date:
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String str = updateEnsurePlanDTO.getEnsureDate();
//        Date date = null;
//        try {
//            date = dateFormat.parse(str);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        faEnsurePlan.setEnsureDate(updateEnsurePlanDTO.getEnsureDate());
        int i = faEnsurePlanMapper.updateById(faEnsurePlan);
//        int i=1;
        return i == 1 ? RootResponse.success(faEnsurePlan_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteEnsurePlan(String ensurePlanId, LoginUserDTO userDTO) {
        var faEnsurePlan_old = faEnsurePlanMapper.selectById(ensurePlanId);
        var queryWrapper = new LambdaQueryWrapper<FaEnsurePlan>();
        queryWrapper.eq(FaEnsurePlan::getId, ensurePlanId);
        queryWrapper.eq(FaEnsurePlan::getIsSoftDelete, false);
        var faEnsurePlan = faEnsurePlanMapper.selectOne(queryWrapper);
        if (faEnsurePlan == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
//        faEnsurePlan.setIsSoftDelete(true);
        // 设为停用状态 status
        faEnsurePlan.setStatus(0);
        faEnsurePlan.setUpdateDateTime(new Date());
        faEnsurePlan.setUpdater(userDTO.getUsername());
        faEnsurePlanMapper.updateById(faEnsurePlan);
        return RootResponse.success(faEnsurePlan_old);
    }

    /**
     * @param ensureRecordPageDTO:
     * @return
     */
    @Override
    public RootResponse<PageResult<FaEnsureRecordVO>> queryFaEnsureRecordPage(EnsureRecordPageDTO ensureRecordPageDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsureRecord>();
        //
        wrapper.eq(FaEnsureRecord::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (ensureRecordPageDTO.getId() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaEnsureRecord::getId, ensureRecordPageDTO.getId());
        }
        wrapper.orderByDesc(FaEnsureRecord::getCreateDateTime, FaEnsureRecord::getId);
        // page helper
        var ensureRecords_pre = faEnsureRecordMapper.selectFaEnsureRecord(ensureRecordPageDTO);
        PageHelper.startPage(ensureRecordPageDTO.getPageNum(), ensureRecordPageDTO.getPageSize());
        List<FaEnsureRecordVO> ensureRecords = new ArrayList<>();
        // 区域判断：
        if (!StringUtils.isEmpty(userDTO.getAreaId())) {
            for (FaEnsureRecordVO ensureRecordVO : ensureRecords_pre) {
                if(!StringUtils.isEmpty(faEnsurePlanMapper.selectById(ensureRecordVO.getPlanId()))){// 过滤脏数据。
                    if (!StringUtils.isEmpty(faEnsurePlanMapper.selectById(ensureRecordVO.getPlanId()).getStructureId())) {
                        if (raRadarMapper.selectById(
                                raTreeMapper.selectById(
                                        faEnsurePlanMapper.selectById(ensureRecordVO.getPlanId()).getStructureId()
                                ).getRadarId()
                        ) != null) {
                            String areaId = raStationMapper.selectById(
                                    raRadarMapper.selectById(
                                            raTreeMapper.selectById(
                                                    faEnsurePlanMapper.selectById(ensureRecordVO.getPlanId()).getStructureId()
                                            ).getRadarId()).getSiteId()
                            ).getAreaId();
                            if (areaId.equals(userDTO.getAreaId())) {
                                ensureRecords.add(ensureRecordVO);
                            }// 如果不是这个区域的就删除。
                        }
                    }
                }
            }
        }
        PageInfo<FaEnsureRecordVO> pageInfo;
        if (!StringUtils.isEmpty(userDTO.getAreaId())) {
            pageInfo = PageInfo.of(ensureRecords);
        } else {
            pageInfo = PageInfo.of(ensureRecords_pre);
        }
        var pageList = pageInfo.getList();
        // add the radarName and the keyPartsModelName
        pageList.forEach(elem -> {
            if (
                    raRadarMapper.selectById(
                            raTreeMapper.selectById(
                                    faEnsurePlanMapper.selectById(elem.getPlanId()
                                    ).getStructureId()
                            ).getRadarId()
                    ) != null
            ) {
                String radarName = raRadarMapper.selectById(
                        raTreeMapper.selectById(
                                faEnsurePlanMapper.selectById(elem.getPlanId()
                                ).getStructureId()
                        ).getRadarId()
                ).getName();
                elem.setRadarName(radarName);
            }
            // add the extension and the system;
            if (faEnsurePlanMapper.selectById(elem.getPlanId())!=null && faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId() != null) {
                if (raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId()).getExtensionId() != null) {
                    String extensionId = raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId()).getExtensionId();
                    String extensionName = raExtensionMapper.selectById(extensionId).getName();
                    elem.setExtensionName(extensionName);
                    elem.setExtensionId(extensionId);
                }
                if (raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId()).getSystemId() != null) {
                    String systemId = raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId()).getSystemId();
                    String systemName = raSystemMapper.selectById(systemId).getName();
                    elem.setSystemName(systemName);
                    elem.setSystemId(systemId);
                }
                if (raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId()).getKeyPartsModelId() != null) {
                    String keyPartsModelId = raTreeMapper.selectById(faEnsurePlanMapper.selectById(elem.getPlanId()).getStructureId()).getKeyPartsModelId();
                   var keyPartsModel= raKeyPartsModelMapper.selectById(keyPartsModelId);
                    String keyPartsModelName = raKeyPartsTypeMapper.selectById(keyPartsModel.getTypeId()).getName()+keyPartsModel.getName();
                    elem.setKeyPartsModelName(keyPartsModelName);
//                    elem.setk(keyPartsModelId);
                }
            }
        });
        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
    }

    @Override
    public RootResponse createEnsureRecord(CreateEnsureRecordDTO createEnsureRecordDTO, LoginUserDTO userDTO) {
        //
//        var wrapper = new LambdaQueryWrapper<FaEnsureRecord>();
//        wrapper.eq(FaEnsureRecord::getContent, createEnsureRecordDTO.getContent());
//        wrapper.eq(FaEnsureRecord::getIsSoftDelete, false);
//        if (faEnsureRecordMapper.selectOne(wrapper) != null) {
//            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障记录已存在，请勿重复添加");
//        }
        //
        var faEnsureRecord = new FaEnsureRecord();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createEnsureRecordDTO, faEnsureRecord);
        faEnsureRecord.setId(HandleUtils.UUID32());
        faEnsureRecord.setCreator(userDTO.getUsername());
        faEnsureRecord.setCreateDateTime(new Date());
        faEnsureRecord.setIsSoftDelete(false);
        // set date:
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String str = createEnsureRecordDTO.getEnsureDate();
//        Date date = null;
//        try {
//            date = dateFormat.parse(str);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        faEnsureRecord.setEnsureDate(createEnsureRecordDTO.getEnsureDate());
        int i = faEnsureRecordMapper.insert(faEnsureRecord);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateEnsureRecord(UpdateEnsureRecordDTO updateEnsureRecordDTO, LoginUserDTO userDTO) {
//        var wrapper1 = new LambdaQueryWrapper<FaEnsureRecord>();
//        wrapper1.eq(FaEnsureRecord::getContent, updateEnsureRecordDTO.getContent());
//        wrapper1.eq(FaEnsureRecord::getIsSoftDelete, false);
//        if (faEnsureRecordMapper.selectOne(wrapper1).getContent().equals(updateEnsureRecordDTO.getContent())) {
////            var FaTaskLevel2 = baseMapper.selectOne(wrapper1);
//            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障记录已存在，请勿重复添加");
//
//        }
        // the old data:
        var faEnsureRecord_old = faEnsureRecordMapper.selectById(updateEnsureRecordDTO.getId());
        var faEnsureRecord = new FaEnsureRecord();
        BeanCopyUtils.copy(updateEnsureRecordDTO, faEnsureRecord);
        faEnsureRecord.setUpdater(userDTO.getUsername());
        faEnsureRecord.setUpdateDateTime(new Date());
        // set date:
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String str = updateEnsureRecordDTO.getEnsureDate();
//        Date date = null;
//        try {
//            date = dateFormat.parse(str);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        faEnsureRecord.setEnsureDate(updateEnsureRecordDTO.getEnsureDate());
        int i = faEnsureRecordMapper.updateById(faEnsureRecord);
        return i == 1 ? RootResponse.success(faEnsureRecord_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteEnsureRecord(String ensureRecordId, LoginUserDTO userDTO) {
        var faEnsureRecord_old = faEnsureRecordMapper.selectById(ensureRecordId);
        var queryWrapper = new LambdaQueryWrapper<FaEnsureRecord>();
        queryWrapper.eq(FaEnsureRecord::getId, ensureRecordId);
        queryWrapper.eq(FaEnsureRecord::getIsSoftDelete, false);
        var faEnsureRecord = faEnsureRecordMapper.selectOne(queryWrapper);
        if (faEnsureRecord == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faEnsureRecord.setIsSoftDelete(true);
        faEnsureRecord.setUpdateDateTime(new Date());
        faEnsureRecord.setUpdater(userDTO.getUsername());
        faEnsureRecordMapper.updateById(faEnsureRecord);
        return RootResponse.success(faEnsureRecord_old);
    }

    /**
     * @param ensureWaysPageDTO:
     * @return
     */
    @Override
    public RootResponse<PageResult<FaEnsureWaysVO>> queryFaEnsureWaysPage(EnsureWaysPageDTO ensureWaysPageDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsureWays>();
        wrapper.eq(FaEnsureWays::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (ensureWaysPageDTO.getName() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaEnsureWays::getName, ensureWaysPageDTO.getName());
        }
        //
        wrapper.orderByDesc(FaEnsureWays::getCreateDateTime, FaEnsureWays::getId);
        // page helper
        PageHelper.startPage(ensureWaysPageDTO.getPageNum(), ensureWaysPageDTO.getPageSize());
        var ensureWayss = faEnsureWaysMapper.selectList(wrapper);
        var pageInfo = PageInfo.of(ensureWayss);
        var pageList = pageInfo.getList();
        System.out.println(pageList);
        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
    }

    @Override
    public RootResponse createEnsureWays(CreateEnsureWaysDTO createEnsureWaysDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<FaEnsureWays>();
        // 查重：
        wrapper.eq(FaEnsureWays::getName, createEnsureWaysDTO.getName());
        wrapper.eq(FaEnsureWays::getIsSoftDelete, false);
        if (faEnsureWaysMapper.selectOne(wrapper) != null) {
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障方法已存在，请勿重复添加");
        }
        //
        var faEnsureWays = new FaEnsureWays();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createEnsureWaysDTO, faEnsureWays);
        faEnsureWays.setId(HandleUtils.UUID32());
        faEnsureWays.setCreator(userDTO.getUsername());
        faEnsureWays.setCreateDateTime(new Date());
        faEnsureWays.setIsSoftDelete(false);
        int i = faEnsureWaysMapper.insert(faEnsureWays);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateEnsureWays(UpdateEnsureWaysDTO updateEnsureWaysDTO, LoginUserDTO userDTO) {
        var wrapper1 = new LambdaQueryWrapper<FaEnsureWays>();
        wrapper1.eq(FaEnsureWays::getName, updateEnsureWaysDTO.getName());
        wrapper1.eq(FaEnsureWays::getIsSoftDelete, false);
        var faEnsureWays1 = faEnsureWaysMapper.selectOne(wrapper1);
        //
        if (faEnsureWays1 != null) {
            if (!faEnsureWays1.getId().equals(updateEnsureWaysDTO.getId())) {
//            var FaTaskLevel2 = baseMapper.selectOne(wrapper1);
                return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障方法已存在，请勿重复添加");

            }
        }

        // the old data:
        var faEnsureWays_old = faEnsureWaysMapper.selectById(updateEnsureWaysDTO.getId());
        var faEnsureWays = new FaEnsureWays();
        BeanCopyUtils.copy(updateEnsureWaysDTO, faEnsureWays);
        faEnsureWays.setUpdater(userDTO.getUsername());
        faEnsureWays.setUpdateDateTime(new Date());
        int i = faEnsureWaysMapper.updateById(faEnsureWays);
        return i == 1 ? RootResponse.success(faEnsureWays_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteEnsureWays(String ensureWaysId, LoginUserDTO userDTO) {
        // 判断是否在保障记录中存在
        LambdaQueryWrapper<FaEnsureRecord> ensureRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ensureRecordLambdaQueryWrapper.eq(FaEnsureRecord::getIsSoftDelete, false);
        ensureRecordLambdaQueryWrapper.eq(FaEnsureRecord::getWayId, ensureWaysId);
        if (faEnsureRecordMapper.selectList(ensureRecordLambdaQueryWrapper).size() > 0) {
            return RootResponse.error("该保养方法在保养或保障记录中存在！！！");
        }
        // ensure plan:
//        LambdaQueryWrapper<FaEnsurePlan> planLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        planLambdaQueryWrapper.eq(FaEnsurePlan::getIsSoftDelete,false);
//        for (FaEnsurePlan faEnsurePlan : faEnsurePlanMapper.selectList(planLambdaQueryWrapper)) {
//            // 通过计划id，查记录中是否存在关联的保障方法
//
//        }

        var faEnsureWays_old = faEnsureWaysMapper.selectById(ensureWaysId);
        var queryWrapper = new LambdaQueryWrapper<FaEnsureWays>();
        queryWrapper.eq(FaEnsureWays::getId, ensureWaysId);
        queryWrapper.eq(FaEnsureWays::getIsSoftDelete, false);
        var faEnsureWays = faEnsureWaysMapper.selectOne(queryWrapper);
        if (faEnsureWays == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faEnsureWays.setIsSoftDelete(true);
        faEnsureWays.setUpdateDateTime(new Date());
        faEnsureWays.setUpdater(userDTO.getUsername());
        faEnsureWaysMapper.updateById(faEnsureWays);
        return RootResponse.success(faEnsureWays_old);
    }

    /**
     * @param phenomenonRecordPageDTO:
     * @return
     */
    @Override
    public RootResponse<PageResult<FaPhenomenonRecordVO>> queryFaPhenomenonRecordPage(FaPhenomenonRecordPageDTO phenomenonRecordPageDTO) {
        var wrapper = new LambdaQueryWrapper<FaPhenomenonRecord>();
        wrapper.eq(FaPhenomenonRecord::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (phenomenonRecordPageDTO.getId() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaPhenomenonRecord::getId, phenomenonRecordPageDTO.getId());
        }
        //
        wrapper.orderByDesc(FaPhenomenonRecord::getCreateDateTime, FaPhenomenonRecord::getId);
        // page helper
        PageHelper.startPage(phenomenonRecordPageDTO.getPageNum(), phenomenonRecordPageDTO.getPageSize());
        var PhenomenonRecords = faPhenomenonRecordMapper.selectList(wrapper);
        var pageInfo = PageInfo.of(PhenomenonRecords);
        var pageList = pageInfo.getList();
        System.out.println(pageList);
        return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
    }

    @Override
    public RootResponse createFaPhenomenonRecord(CreateFaPhenomenonRecordDTO createFaPhenomenonRecordDTO, LoginUserDTO userDTO) {
//        var wrapper = new LambdaQueryWrapper<FaPhenomenonRecord>();
//        wrapper.eq(FaPhenomenonRecord::g, createFaPhenomenonRecordDTO.getRemarks());
//        wrapper.eq(FaPhenomenonRecord::getIsSoftDelete, false);
//        if (faPhenomenonRecordMapper.selectOne(wrapper) != null) {
//            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "故障信息已存在，请勿重复添加");
//        }
        //
        var faPhenomenonRecord = new FaPhenomenonRecord();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createFaPhenomenonRecordDTO, faPhenomenonRecord);
        faPhenomenonRecord.setId(HandleUtils.UUID32());
        faPhenomenonRecord.setCreator(userDTO.getUsername());
        faPhenomenonRecord.setCreateDateTime(new Date());
        faPhenomenonRecord.setIsSoftDelete(false);
        int i = faPhenomenonRecordMapper.insert(faPhenomenonRecord);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateFaPhenomenonRecord(UpdateFaPhenomenonRecordDTO updateFaPhenomenonRecordDTO, LoginUserDTO userDTO) {
//        var wrapper1 = new LambdaQueryWrapper<FaPhenomenonRecord>();
//        wrapper1.eq(FaPhenomenonRecord::getId, updateFaPhenomenonRecordDTO.getId());
//        wrapper1.eq(FaPhenomenonRecord::getIsSoftDelete, false);
//        if (faPhenomenonRecordMapper.selectOne(wrapper1).getRemarks().equals(updateFaPhenomenonRecordDTO.getRemarks())) {
////            var FaTaskLevel2 = baseMapper.selectOne(wrapper1);
//            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "保障记录已存在，请勿重复添加");
//
//        }
        // the old data:
        var faPhenomenonRecord_old = faPhenomenonRecordMapper.selectById(updateFaPhenomenonRecordDTO.getId());
        var faPhenomenonRecord = new FaPhenomenonRecord();
        BeanCopyUtils.copy(updateFaPhenomenonRecordDTO, faPhenomenonRecord);
        faPhenomenonRecord.setUpdater(userDTO.getUsername());
        faPhenomenonRecord.setUpdateDateTime(new Date());
        int i = faPhenomenonRecordMapper.updateById(faPhenomenonRecord);
        return i == 1 ? RootResponse.success(faPhenomenonRecord_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteFaPhenomenonRecord(String faPhenomenonRecordId, LoginUserDTO userDTO) {
        var faPhenomenonRecord_old = faPhenomenonRecordMapper.selectById(faPhenomenonRecordId);
        var queryWrapper = new LambdaQueryWrapper<FaPhenomenonRecord>();
        queryWrapper.eq(FaPhenomenonRecord::getId, faPhenomenonRecordId);
        queryWrapper.eq(FaPhenomenonRecord::getIsSoftDelete, false);
        var faPhenomenonRecord = faPhenomenonRecordMapper.selectOne(queryWrapper);
        if (faPhenomenonRecord == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faPhenomenonRecord.setIsSoftDelete(true);
        faPhenomenonRecord.setUpdateDateTime(new Date());
        faPhenomenonRecord.setUpdater(userDTO.getUsername());
        faPhenomenonRecordMapper.updateById(faPhenomenonRecord);
        return RootResponse.success(faPhenomenonRecord_old);
    }

    /**
     * @param phenomenonPageDTO:
     * @return
     */
    @Override
    public RootResponse<PageResult<FaPhenomenonVO>> queryFaPhenomenonPage(FaPhenomenonPageDTO phenomenonPageDTO) {
        var wrapper = new LambdaQueryWrapper<FaPhenomenon>();
        wrapper.eq(FaPhenomenon::getIsSoftDelete, false);
        // fuzzy query 模糊查询；
        if (phenomenonPageDTO.getSpecialId() != null) {
            // if not null, then get the specially query by the name;
            wrapper.like(FaPhenomenon::getSpecialId, phenomenonPageDTO.getSpecialId());
        }

        //
        wrapper.orderByDesc(FaPhenomenon::getCreateDateTime, FaPhenomenon::getId);
        // page helper
        if ("00".equals(phenomenonPageDTO.getType())) {
            PageHelper.startPage(phenomenonPageDTO.getPageNum(), phenomenonPageDTO.getPageSize());
            var Phenomenons = faPhenomenonMapper.selectAndRadarName(phenomenonPageDTO);
//            List<FaPhenomenonVO> lst = new ArrayList<>();
//            for (FaPhenomenon phenomenon : Phenomenons) {
//                FaPhenomenonVO faPhenomenonVO = new FaPhenomenonVO();
//                BeanCopyUtils.copy(phenomenon,faPhenomenonVO);
//                lst.add(faPhenomenonVO);
//            }
            // radarType name;
            var pageInfo = PageInfo.of(Phenomenons);
            var pageList = pageInfo.getList();
//            for (FaPhenomenonVO phenomenonVO : pageList) {
//                if (phenomenonVO.getRadarType()!=null&&!phenomenonVO.getRadarType().equals("")){
//                    LambdaQueryWrapper<FiRadarType> queryWrapper = new LambdaQueryWrapper<>();
//                    queryWrapper.eq(FiRadarType::getIsSoftDelete,false);
//                    queryWrapper.eq(FiRadarType::getId, phenomenonVO.getRadarType());
//                    if (fiRadarTypeMapper.selectOne(queryWrapper)!=null){
//                        FiRadarType radarType = fiRadarTypeMapper.selectOne(queryWrapper);
//                        phenomenonVO.setRadarTypeName(radarType.getName());
//                    }
//
//                }
//            }
            return RootResponse.success(PageResult.page(pageList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
        } else {
            var roles = faPhenomenonMapper.selectList(wrapper);
            return RootResponse.success(roles);
        }
    }

    @Override
    public RootResponse createFaPhenomenon(CreateFaPhenomenonDTO createFaPhenomenonDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<FaPhenomenon>();
        wrapper.eq(FaPhenomenon::getSpecialId, createFaPhenomenonDTO.getSpecialId());
        wrapper.eq(FaPhenomenon::getIsSoftDelete, false);
        if (faPhenomenonMapper.selectOne(wrapper) != null) {
            return RootResponse.error("故障现象已存在，请勿重复添加");
        }
        //
        var faPhenomenon = new FaPhenomenon();
//        BeanCopyUtils.copy(src,dest);
        BeanCopyUtils.copy(createFaPhenomenonDTO, faPhenomenon);
        faPhenomenon.setId(HandleUtils.UUID32());
        faPhenomenon.setCreator(userDTO.getUsername());
        faPhenomenon.setCreateDateTime(new Date());
        faPhenomenon.setIsSoftDelete(false);
        int i = faPhenomenonMapper.insert(faPhenomenon);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateFaPhenomenon(UpdateFaPhenomenonDTO updateFaPhenomenonDTO, LoginUserDTO userDTO) {
        var wrapper1 = new LambdaQueryWrapper<FaPhenomenon>();
        wrapper1.eq(FaPhenomenon::getSpecialId, updateFaPhenomenonDTO.getSpecialId());
        wrapper1.eq(FaPhenomenon::getRadarType,updateFaPhenomenonDTO.getRadarType());
        wrapper1.eq(FaPhenomenon::getIsSoftDelete, false);
        FaPhenomenon faPhenomenon1 = faPhenomenonMapper.selectOne(wrapper1);
        if (faPhenomenon1 != null) {
            if (!faPhenomenon1.getId().equals(updateFaPhenomenonDTO.getId())) {
//            var FaTaskLevel2 = baseMapper.selectOne(wrapper1);
                return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(), "故障现象已存在，请勿重复添加");

            }
        }
        // the old data:
        var faPhenomenon_old = faPhenomenonMapper.selectById(updateFaPhenomenonDTO.getId());
        var faPhenomenon = new FaPhenomenon();
        BeanCopyUtils.copy(updateFaPhenomenonDTO, faPhenomenon);
        faPhenomenon.setUpdater(userDTO.getUsername());
        faPhenomenon.setUpdateDateTime(new Date());
        int i = faPhenomenonMapper.updateById(faPhenomenon);
        return i == 1 ? RootResponse.success(faPhenomenon_old) : RootResponse.error();
    }

    @Override
    public RootResponse deleteFaPhenomenon(String faPhenomenonId, LoginUserDTO userDTO) {
        // 故障现象删除，与故障记录的绑定关系：
        LambdaQueryWrapper<FaPhenomenonRecord> ifDelete = new LambdaQueryWrapper<>();
        ifDelete.eq(FaPhenomenonRecord::getPhenomenonId, faPhenomenonId);
        ifDelete.eq(FaPhenomenonRecord::getIsSoftDelete, false);
        List<FaPhenomenonRecord> faPhenomenonRecords = faPhenomenonRecordMapper.selectList(ifDelete);
        for (FaPhenomenonRecord phenomenonRecord : faPhenomenonRecords) {
            if (!StringUtils.isEmpty(phenomenonRecord.getFaultRecordId())) {
                FaFaultRecord faultRecord = faFaultRecordMapper.selectById(phenomenonRecord.getFaultRecordId());
                if (faultRecord != null) {
                    if (!faultRecord.getIsSoftDelete()) {
                        return RootResponse.error("有故障记录绑定该故障现象，请勿删除！");
                    }
                }
            }
        }
        //
        var faPhenomenon_old = faPhenomenonMapper.selectById(faPhenomenonId);
        var queryWrapper = new LambdaQueryWrapper<FaPhenomenon>();
        queryWrapper.eq(FaPhenomenon::getId, faPhenomenonId);
        queryWrapper.eq(FaPhenomenon::getIsSoftDelete, false);
        var faPhenomenon = faPhenomenonMapper.selectOne(queryWrapper);
        if (faPhenomenon == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        faPhenomenon.setIsSoftDelete(true);
        faPhenomenon.setUpdateDateTime(new Date());
        faPhenomenon.setUpdater(userDTO.getUsername());
        faPhenomenonMapper.updateById(faPhenomenon);
        return RootResponse.success(faPhenomenon_old);
    }
}
